//
//  ProductCollectionView.m
//  LazyCat
//
//  Created by zhanshu on 15/9/11.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "ProductCollectionView.h"
#import "Html5ViewController.h"
@implementation ProductCollectionView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (id)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self) {
        self.backgroundColor = BackColor;
        self.delegate = self;
        self.dataSource = self;
        self.alwaysBounceVertical = YES;
        [self registerNib:[UINib nibWithNibName:@"ProductCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"cell"];
        
        dataArr = [[NSMutableArray alloc] init];
        buyCountArr = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)theDataIs:(NSArray *)arr doLoadMoreRefresh:(BOOL)doLoadMoreRefresh{
    if (doLoadMoreRefresh) {
        [dataArr removeAllObjects];
        [buyCountArr removeAllObjects];
    }
    [dataArr addObjectsFromArray:arr];
    for (int i = 0; i < dataArr.count; i ++) {
        [buyCountArr addObject:@"0"];
    }
    [self reloadData];
}
#pragma mark --collection  datasource  delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return dataArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWidth = (ScreenWidth - 30)/2;
    CGFloat itemHeight = 210*itemWidth/145;
    return CGSizeMake(itemWidth, itemHeight);
}
//定义每个Section 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 10, 10, 10);//分别为上、左、下、右
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Cell = @"cell";
    ProductCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:Cell forIndexPath:indexPath];
    cell.delegate = self;
    if (dataArr.count>0) {
        NSDictionary *dic = dataArr[indexPath.row];
        cell.productImg.image = [UIImage imageNamed:@"product-no-pic.png"];
        [cell.productImg sd_setImageWithURL:[NSURL URLWithString:[dic[@"img"] safeString]] placeholderImage:[UIImage imageNamed:@"product-no-pic.png"]];
        cell.productName.text = dic[@"name"];
        cell.productDetailLable.text = dic[@"roperty"];
        cell.nowPriceLable.text = [NSString stringWithFormat:@"%@",dic[@"sale"]];
        
#pragma mark - 所搜页面商品加减数量显示
        NSInteger count = [buyCountArr[indexPath.row] intValue];
        if (count == 0) {
            cell.reduceBtn.hidden = YES;
            cell.countLable.hidden = YES;
        }else {
            cell.reduceBtn.hidden = NO;
            cell.countLable.hidden = NO;
        }
        cell.countLable.text = buyCountArr[indexPath.row];
    }
    
    return cell;
}

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [dataArr objectAtIndex:indexPath.row];
    NSString *requestUrl = dic[@"url"];
    NSString *titleName = dic[@"name"];
    
    Html5ViewController *html5VC = [[Html5ViewController alloc] init];
    html5VC.doDetailType = YES;
    html5VC.titleStr = titleName;
    html5VC.requestUrl = requestUrl;
    [self.viewController.navigationController pushViewController:html5VC animated:YES];
}
#pragma mark - 选择数量 delegate
- (void)collectionCell:(ProductCollectionViewCell *)cell btn:(UIButton *)btn countLable:(UILabel *)countLable{
    
    if (![AppData share].doLogin) {
        [[MessShowView share] showWithMess:@"请先登录"];
        [(BaseViewController*)self.viewController goLoginView];
        return;
    }
    NSIndexPath *indexPath = [self indexPathForCell:cell];
    NSInteger tag = btn.tag;
    
    NSDictionary *productDic = dataArr[indexPath.row];
//    NSString *string = [NSString stringWithFormat:ModifyShoppingCartCount,[AppData share].username,[ShopCommonModel getShopMess].shopuser,productDic[@"id"],tag==100?0:1,[Utils md5SignStr]];
    NSString *string = @"";
    
    [NTNetUtil sendRequestWithUrl:string requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSString *suc = dic[@"r"];
        if ([suc isEqualToString:@"T"]) {
            //成功后改变商品数量
            [self changeProductCount:tag backCount:dic[@"totalcount"] indexPath:indexPath locCount:buyCountArr[indexPath.row]];
            
            if ([_searchProductDelegate respondsToSelector:@selector(currentShoppingCount:)]) {
                [_searchProductDelegate currentShoppingCount:dic[@"totalcount"]];
            }
        }else {
            [[MessShowView share] showWithMess:dic[@"m"]];
        }
    }];
    
}
- (void)changeProductCount:(NSInteger)tag backCount:(NSString *)count indexPath:(NSIndexPath*)indexPath locCount:(NSString *)locCount{
    if (tag == 100) {
        if (count == 0) {
            [buyCountArr replaceObjectAtIndex:indexPath.row withObject:locCount];
        }else {
            int ct = [locCount intValue]-1;
            [buyCountArr replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%d",ct]];
        }
        
        [[AppData share].baseTabVC doReduce:YES];
    }else {
        int ct = [locCount intValue]+1;
        [buyCountArr replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%d",ct]];
    }
    
    [[AppData share].baseTabVC theShoppingCartCount:count];
    
    [self reloadData];
}
@end
